/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package axil.stdlib.core.construct;

import axil.api.AxilObject;
import axil.api.extend.Environment;
import axil.api.extend.Function;
import axil.api.extend.Parameters;
import axil.api.extend.Source;
import axil.compiler.api.Emitter;
import axil.compiler.api.ScopeInjector;
import axil.compiler.ast.IdentifierNode;
import axil.compiler.ast.Node;
import axil.engine.function.Func;
import axil.stdlib.collection.type.Range;
import axil.vm.opcode.Opcode;
import axil.vm.stack.StackFrame;

import java.util.List;

import static axil.framework.Functions.last;


/**
 * An anonymous function. These are in the form of:
 *
 * 		func(arg-a, arg-b, arg-c, body)
 *
 * For example:
 *
 * 		inject(cart.items, $0.00, func(total, item, total + item.cost))
 */
public class FuncF implements Function, ScopeInjector, Emitter {
	/**
	 * Tell if the variable identifiers are given directly in this function (as
	 * with "let" or "func") or are indirectly declared in a subsidiary function
	 * (as with "with").
	 */
	public boolean indirect() {
		return false;
	}


	/**
	 * Indicate any new identifiers defined by the given arguments. The range
	 * of values in which identifiers can be expected is returned. A null value
	 * is returned if the number of arguments given is not valid for this
	 * function.
	 */
	public Range injects(int args) {
		return new Range(0, args - 2);
	}


	/**
	 * Emit a new instance of this function using the indicated arguments. This
	 * method can safely assume that the number of arguments required are being
	 * provided.
	 */
	public Opcode emit(Source source, List<Node> args) {
		/**
		 * What we have here is a functor, or anonymous function. This is in the
		 * form of:
		 *
		 * 		func(a, b, c, a + b + c)
		 *
		 * At this point, the arguments of a,b,c have already been handled by
		 * the compiler and the expression (body) of the function has also been
		 * compiled. So, all we need to do is emit a special functor object
		 * representing the body as an object.
		 */
		final int size = args.size() - 1;
		int[] ids = new int[size];
		String[] symbols = new String[size];
		for (int i = 0; i < size; i++) {
			IdentifierNode arg = (IdentifierNode)args.get(i);
			ids[i] = arg.id();
			symbols[i] = arg.identity();
		}
		return new Func(source, symbols, ids, last(args).emit());
	}


	/**
	 * Execute this function with the given arguments. The Axil compiler will
	 * ensure that the number of arguments passed to the function are valid.
	 * If this function fails during execution for any reason, then an exception
	 * is thrown.
	 */
	public AxilObject eval(Environment env, Parameters params, Source source) {
		final int size = params.size() - 1;
		Func func = (Func)params.at(size);
		StackFrame sf = StackFrame.create(params, source, func.ids());
		for (int i = 0; i < size; i++) {
			sf.at(i, params.at(i).eval(env, params));
		}
		return func.call(env, sf);
	}
}
